import json
import shutil
from docx import Document

from bs4 import BeautifulSoup


# pip install beautifulsoup4


def resolveAOJson(filePath: str):
    with open(filePath, "r", encoding="utf-8") as file:
        data = json.load(file)  # 直接解析为 Python 对象

    return data


configFilePath = 'C:\\Users\\Administrator\\Desktop'


def testJson():
    filePath = 'C:\\Users\\Administrator\\Desktop\\output.json'
    data = resolveAOJson(filePath)

    # 获取工序表内容
    operations = data['Operations']
    operationsOutput = []
    for operation in operations:
        operationOutput = {}

        # 序号  实例名
        num = operation['PLM_ExternalID']
        operationOutput['no'] = num

        # 工序名 参考名
        name = operation['reference']['V_Name']
        operationOutput['name'] = name

        # 取出工艺内容
        instructions = operation['Instructions']
        if instructions and len(instructions) > 0:
            instructionOne = instructions[0]
            txt = instructionOne['reference']['V_WIInstruction_Text']
            soup = BeautifulSoup(txt, 'html.parser')
            body = soup.body
            p_tags = body.find_all('p')  # 获取所有 <p> 标签
            p_texts = [p.get_text() for p in p_tags]
            bodyText = "\n".join(p_texts)
            operationOutput['WorkInstruction'] = bodyText

        operationsOutput.append(operationOutput)

    print(operationsOutput)

    # operations = data['Operations']
    # print(operations)
    #
    # i = 1
    # for operation in operations:
    #     instructions = operation['Instructions']
    #     for instruction in instructions:
    #         print(f'instruction: {instruction}')
    #         txt = instruction['reference']['V_WIInstruction_Text']
    #         print(txt)
    #         soup = BeautifulSoup(txt, 'html.parser')
    #         body = soup.body
    #         p_tags = body.find_all('p')  # 获取所有 <p> 标签
    #         p_texts = [p.get_text() for p in p_tags]
    #         print("=================")
    #         print(p_texts)
    #
    #         source_file_path = configFilePath + '\\txthtml.docx'
    #         copied_file_path = configFilePath + f'\\txthtml-{i}.docx'
    #         i = i + 1
    #         shutil.copy2(source_file_path, copied_file_path)
    #
    #         # 打开文档
    #         doc = Document(copied_file_path)
    #
    #         # 获取第一个表格用于写入
    #         if not doc.tables:
    #             raise ValueError("文档中没有表格")
    #
    #         table = doc.tables[0]
    #         first_row = table.rows[0]  # 第一行
    #         first_cell = first_row.cells[0]
    #
    #         bodyText = "\n".join(p_texts)
    #
    #         first_cell.text = bodyText
    #         doc.save(copied_file_path)


if __name__ == '__main__':
    testJson()
